//
//  FQDLabOpinionViewController.m
//  FakeQDaily
//
//  Created by mewxiv on 9/13/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDLabOpinionViewController.h"
#import "FQDLabOpinionsCellItemProvider.h"
#import "FQDMultiColumnsCollectionViewLayout.h"
#import "FQDLabOpinionHeadCell.h"
#import "FQDLabOpinionCell.h"
#import "FQDLabFeedCell.h"
#import "FQDLabPublishCell.h"
#import "FQDSeparatorCell.h"
#import "FQDRefreshFooter.h"
#import "FQDLabFeedCellItem.h"
#import "FQDRestModel.h"

#import "Masonry.h"

@interface FQDLabOpinionViewController () <UICollectionViewDelegate,
                                           UICollectionViewDataSource,
                                           UICollectionViewDelegateFlowLayout,
                                           UIScrollViewDelegate,
                                           FQDMultiColumnsCollectionViewLayoutDelegate,
                                           FQDBaseCellActionDelegate>

// 用于记录当前已经展开过的FQDLabOpinionCell单元格
@property (nonatomic, strong) NSMutableSet *expandedIndexPathSet;
@property (nonatomic, strong) NSArray *opinions;
// 显示所有内容的collectionView
@property (nonatomic, strong) UICollectionView *collectionView;
// 顶部标题单元格，弹幕显示在上面
@property (nonatomic, weak) FQDLabOpinionHeadCell *headCell;
// 意见提供源
@property (nonatomic, strong) FQDLabOpinionsCellItemProvider *provider;
// 加载更多页脚
@property (nonatomic, strong) FQDRefreshFooter *refreshFooter;
// 计算size的单元格
@property (nonatomic, strong) FQDLabFeedCell *sizingCell;
// 返回按钮
@property (nonatomic, strong) UIButton *backButton;

@end

@implementation FQDLabOpinionViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
   
    self.expandedIndexPathSet = [NSMutableSet set];
    
    [self setupCellItemProvider];
    [self setupCollectionView];
    [self setupRefreshView];
    [self setupToolbar];
    [self loadPaperDetail];
    [self loadNewOpinions];
    
}

- (void)setupCellItemProvider
{
    FQDFeed *feed = self.labFeedCellItem.feed;
    self.provider = [[FQDLabOpinionsCellItemProvider alloc] init];
    self.provider.feedId = feed.post.ID;
}

- (void)setupCollectionView
{
    FQDMultiColumnsCollectionViewLayout *columnsLayout = [[FQDMultiColumnsCollectionViewLayout alloc] init];
//    columnsLayout.columnCount = 2;
    columnsLayout.minimumColumnSpacing = 10.0f;
    columnsLayout.minimumLineSpacing = 0;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:columnsLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[FQDLabOpinionCell class]
            forCellWithReuseIdentifier:[FQDLabOpinionCell reuseId]];
    [self.collectionView registerClass:[FQDLabOpinionHeadCell class]
            forCellWithReuseIdentifier:[FQDLabOpinionHeadCell reuseId]];
    [self.collectionView registerClass:[FQDLabFeedCell class]
            forCellWithReuseIdentifier:[FQDLabFeedCell reuseId]];
    [self.collectionView registerClass:[FQDLabPublishCell class]
            forCellWithReuseIdentifier:[FQDLabPublishCell reuseId]];
    [self.collectionView registerClass:[FQDSeparatorCell class]
            forCellWithReuseIdentifier:[FQDSeparatorCell reuseId]];
}

- (void)setupRefreshView
{
    self.refreshFooter = [FQDRefreshFooter footerWithRefreshingTarget:self
                          refreshingAction:@selector(loadMoreOpinions)];
    self.collectionView.mj_footer = self.refreshFooter;
}

- (void)setupToolbar
{
    UIImage *backImage = [UIImage imageNamed:@"navigation_back_round_normal"];
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backButton setImage:backImage forState:UIControlStateNormal];
    [self.view addSubview:self.backButton];
    
    
    [self.backButton addTarget:self
                        action:@selector(goBack:)
              forControlEvents:UIControlEventTouchUpInside];
    
    WeakSelf;
    [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view).offset(14);
        make.bottom.equalTo(weakSelf.view).offset(-4);
    }];
    
    self.backButton.alpha = 0;
    
    [UIView animateWithDuration:0.3f delay:0.3f options:0 animations:^{
        self.backButton.alpha = 1.0f;
    } completion:nil];
}

- (void)loadPaperDetail
{
    WeakSelf;
    FQDFeed *feed = self.labFeedCellItem.feed;
    NSString *qdID = feed.post.ID;
    [[QDailyAPI sharedAPI] getLabPaperDetail:qdID completion:^(id responseObject, NSError *error) {
        id response = responseObject[@"response"];
        NSArray *options = response[@"options"];
        weakSelf.opinions = [NSArray yy_modelArrayWithClass:[FQDLabOpinion class]
                                                       json:options];
        weakSelf.headCell.opinions = weakSelf.opinions;
        
        NSString *feedImage = response[@"image"];
        NSNumber *feedType = response[@"type"];
        FQDPost *post = [FQDPost yy_modelWithJSON:response[@"post"]];
        self.labFeedCellItem.feed.image = feedImage;
        self.labFeedCellItem.feed.type = [feedType integerValue];
        self.labFeedCellItem.feed.post = post;
        [self.collectionView reloadData];
    }];
}

- (void)loadNewOpinions
{
    WeakSelf;
    [self.provider loadNewCellItems:^(BOOL isSuccess) {
        [weakSelf.collectionView reloadData];
    }];
}

- (void)loadMoreOpinions
{
    WeakSelf;
    if ([self.provider hasMoreCellItems]) {
        [self.provider loadMoreCellItems:^(BOOL isSuccess) {
            [weakSelf.collectionView reloadData];
            [weakSelf.refreshFooter endRefreshing];
        }];
    } else {
        [self.refreshFooter endRefreshingWithNoMoreData];
    }
}

#pragma mark - Event response
- (void)goBack:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - FQDBaseCellActionDelegate
- (void)collectionViewCell:(UICollectionViewCell *)cell actionType:(NSInteger)actionType actionControl:(UIControl *)control userInfo:(NSDictionary *)userInfo
{
    if ([cell isKindOfClass:[FQDLabOpinionCell class]]) {
        if (actionType == FQDLabOpinionCellActionClickExpandButton) {
            [self.collectionView performBatchUpdates:^{
                NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
                [self.expandedIndexPathSet addObject:indexPath];
                [self.collectionView.collectionViewLayout invalidateLayout];
            } completion:nil];
        }
    }
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 4;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section < 3) {
        return 1;
    } else {
        return [self.provider.cellItems count]+1;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell;
    if (indexPath.section == 0) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:[FQDLabOpinionHeadCell reuseId]
                forIndexPath:indexPath];
        FQDFeed *feed = self.labFeedCellItem.feed;
        self.headCell = (FQDLabOpinionHeadCell *)cell;
        self.headCell.post = feed.post;
        self.headCell.opinions = self.opinions;
        
    } else if (indexPath.section == 1) {
        FQDLabFeedCell *labFeedCell = (FQDLabFeedCell *)
        [collectionView dequeueReusableCellWithReuseIdentifier:[FQDLabFeedCell reuseId]
         forIndexPath:indexPath];
        
        labFeedCell.showContentImage = NO;
        labFeedCell.cellItem = self.labFeedCellItem;
        cell = labFeedCell;
        
    } else if (indexPath.section == 2) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:[FQDSeparatorCell reuseId]
                forIndexPath:indexPath];
        cell.backgroundColor = RGB(242, 242, 242);
    } else {
        if (indexPath.item == 0) {
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:[FQDLabPublishCell reuseId]
                                                             forIndexPath:indexPath];
        } else {
            cell = [collectionView dequeueReusableCellWithReuseIdentifier:[FQDLabOpinionCell reuseId]
                                                             forIndexPath:indexPath];
            
            FQDLabOpinionCell *opinionCell = (FQDLabOpinionCell *)cell;
            opinionCell.opinion = self.provider.cellItems[indexPath.item-1];
            opinionCell.colorIndex = indexPath.item-1;
            opinionCell.delegate = self;
            
            BOOL expanded = [self.expandedIndexPathSet containsObject:indexPath];
            expanded ? [opinionCell expandCell:NO] : nil;
        }
    }
    
    return cell;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.headCell) {
        CGFloat maxHeight = [FQDLabOpinionHeadCell cellHeight];
        CGFloat offset = scrollView.contentOffset.y;
        if (maxHeight - offset >= 0) {
            CGRect frame = self.headCell.frame;
            frame.origin.y = offset;
            frame.size.height = maxHeight - offset;
            self.headCell.frame = frame;
        }
    }
}

#pragma mark - FQDMultiColumnsCollectionViewLayoutDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView columnCountForSection:(NSInteger)section
{
    NSInteger sectionCount = [collectionView numberOfSections];
    if (section == sectionCount - 1) {
        return 2;
    }
    
    return 1;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    NSInteger sectionCount = [collectionView numberOfSections];
    if (section == sectionCount - 1) {
       return UIEdgeInsetsMake(0, 10.0f, 0, 10.0f);
    }
    return UIEdgeInsetsZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize size;
    FQDMultiColumnsCollectionViewLayout *layout = (FQDMultiColumnsCollectionViewLayout *)collectionViewLayout;
    CGFloat itemWidth = [layout columnWidthForSection:indexPath.section];
    if (indexPath.section == 0) {
        size = CGSizeMake(itemWidth, [FQDLabOpinionHeadCell cellHeight]);
    } else if (indexPath.section == 1) {
        size = [self collectionView:collectionView layout:layout sizeForLabFeedCellAtIndexPath:indexPath];
    } else if (indexPath.section == 2) {
        size = CGSizeMake(itemWidth, 5.0f);
    } else {
        size = [self collectionView:collectionView layout:layout sizeForOpinionCellAtIndexPath:indexPath];
    }
    return size;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(FQDMultiColumnsCollectionViewLayout *)collectionViewLayout sizeForLabFeedCellAtIndexPath:(NSIndexPath *)indexPath
{
    if (!self.sizingCell) {
        CGFloat itemWidth = [collectionViewLayout columnWidthForSection:indexPath.section];
        self.sizingCell = (self.sizingCell) ? : [[FQDLabFeedCell alloc] init];
        self.sizingCell.cellItem = self.labFeedCellItem;
        self.sizingCell.showContentImage = NO;
        CGSize cellSize = [self.sizingCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
        cellSize.width = itemWidth;
        self.sizingCell.frame = (CGRect){CGPointZero, cellSize};
    }
    return self.sizingCell.frame.size;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(FQDMultiColumnsCollectionViewLayout *)collectionViewLayout sizeForOpinionCellAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat itemWidth = [collectionViewLayout columnWidthForSection:indexPath.section];
    BOOL isExpand = [self.expandedIndexPathSet containsObject:indexPath];
    if (!isExpand) {
        return CGSizeMake(itemWidth, itemWidth+10);
    }
    
    FQDLabOpinion *opinion = self.provider.cellItems[indexPath.item-1];
    CGFloat textHeight = [FQDLabOpinionCell heightForOpinion:opinion
                                             fittingWidth:itemWidth];
    
    return CGSizeMake(itemWidth, MAX(textHeight, itemWidth+10));
}

@end
